package net.babeuf.form.factory 
{
	import flash.utils.describeType;
	import net.babeuf.form.conditions.AbstractCondition;
	import net.babeuf.form.fields.AbstractField;
	import net.babeuf.form.Form;
	import net.babeuf.form.sensors.AbstractSensor;
	/**
	 * ...
	 * @author Damien Pegoraro
	 */
	public class MetaFormFactory 
	{	
		
		
		
		public static function buildFromMetas( object : *, form : Form ) : void
		{
			var xml : XML = describeType( object ) ; 
			parseMetaFields( xml, object, form ) ;		
			parseMetaConditions( xml, object, form ) ; 
			parseMetaSensors( xml, object, form ) ; 
			
			form.empty() ; 
		}
		
		static private function fillMetaList( xml : XML, metaName :  String,  object : * ) : Array 
		{
			var tmp : Array = new Array() ; 
			for each ( var meta : XML in xml..metadata.( @name == metaName ) )
			{
				var o : Object = new Object() ; 				
				var id : String = String(meta.parent().@name) ;  
				o.target = object[id] ; 				
								
				for each ( var arg : XML in meta..arg )
				{
					if ( String(arg.@key) == "id" ) id = String(arg.@value) ;
					o[String(arg.@key)] = String(arg.@value) ; 					
				}
				
				o.id = id ; 
				tmp.push(o) ; 			
			}
			
			tmp.sortOn("order", Array.NUMERIC) ; 
			return tmp ; 			
		}
		
		static private function parseMetaConditions(xml:XML, object:*, form:Form):void 
		{
			var tmp : Array = fillMetaList(xml, "Condition", object) ; 
			
			for ( var i : uint = 0 ; i < tmp.length ; ++i ) 
			{
				tmp[i].form = form ; 
				var condition : AbstractCondition = MetaConditionFactory.buildConditionFromObject(tmp[i]) ; 
				if ( condition ) form.addCondition( condition,tmp[i].id, tmp[i].error);
			}				
			
		}
		
		static private function parseMetaFields(xml:XML, object : *, form:Form):void 
		{
			var tmp : Array = fillMetaList(xml, "Field", object) ; 
			
			for ( var i : uint = 0 ; i < tmp.length ; ++i ) 
			{
				var field : AbstractField = MetaFieldFactory.buildFieldFromObject(tmp[i]) ; 
				if ( field ) form.addField( field,tmp[i].id);
			}			
			
		}
		
		static private function parseMetaSensors(xml:XML, object : *, form:Form):void 
		{
			var tmp : Array = fillMetaList(xml, "Sensor", object) ; 
			
			for ( var i : uint = 0 ; i < tmp.length ; ++i ) 
			{
				var o : Object = tmp[i] ; 
				
				var sensor : AbstractSensor = MetaSensorFactory.buildSensorFromObject(tmp[i]) ; 
				if ( sensor ) 				
				{
					if ( form.getCondition( String(o.condition)) )  form.getCondition( String(o.condition)).addSensor( sensor ) ; 
					else if ( form.getField( String(o.field)) ) form.getField( String(o.field)).addSensor( sensor ) ; 				
					else if ( form.getField( String(o.id)) ) form.getField( String(o.id)).addSensor( sensor ) ; 				
				}
			}			
			
		}
		
	}

}